<template>
  <div class="reception-outing">
    <div class="header">
      <h2>外出管理</h2>
      <div class="header-actions">
        <el-button type="primary" @click="showRegisterDialog = true">
          <el-icon><Plus /></el-icon>
          外出登记
        </el-button>
      </div>
    </div>

    <div class="content">
      <!-- 外出申请管理 -->
      <div class="outing-section">
        <el-card class="outing-card">
          <template #header>
            <div class="card-header">
              <span>外出申请管理</span>
              <div class="filter-actions">
                <el-select v-model="applyFilter.status" placeholder="申请状态" style="width: 120px">
                  <el-option label="全部" value=""></el-option>
                  <el-option label="待处理" value="pending"></el-option>
                  <el-option label="已批准" value="approved"></el-option>
                  <el-option label="已拒绝" value="rejected"></el-option>
                </el-select>
                <el-button type="primary" @click="loadOutingApplies">搜索</el-button>
              </div>
            </div>
          </template>

          <el-table :data="outingApplyList" v-loading="applyLoading">
            <el-table-column type="index" label="序号" width="60" align="center" />
            <el-table-column prop="elderName" label="老人姓名" width="100" align="center" />
            <el-table-column prop="familyName" label="家属姓名" width="100" align="center" />
            <el-table-column prop="familyPhone" label="家属电话" width="120" align="center" />
            <el-table-column prop="outingReason" label="外出事由" min-width="150" show-overflow-tooltip />
            <el-table-column prop="outingTime" label="外出时间" width="180" align="center">
              <template #default="{ row }">
                {{ formatDateTime(row.outingTime) }}
              </template>
            </el-table-column>
            <el-table-column prop="expectedReturnTime" label="预计返回" width="180" align="center">
              <template #default="{ row }">
                {{ formatDateTime(row.expectedReturnTime) }}
              </template>
            </el-table-column>
            <el-table-column prop="applyStatus" label="申请状态" width="100" align="center">
              <template #default="{ row }">
                <el-tag :type="getApplyStatusTag(row.applyStatus)">
                  {{ getApplyStatusText(row.applyStatus) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200" align="center" fixed="right">
              <template #default="{ row }">
                <el-button link type="primary" @click="viewApplyDetail(row)" v-if="row.applyStatus === 'pending'">
                  处理
                </el-button>
                <el-button link type="info" @click="viewApplyDetail(row)" v-else>
                  查看
                </el-button>
                <el-button link type="warning" @click="extendOuting(row)" v-if="row.applyStatus === 'approved'">
                  延期
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <div class="pagination">
            <el-pagination
              v-model:current-page="applyPagination.current"
              v-model:page-size="applyPagination.size"
              :total="applyPagination.total"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleApplySizeChange"
              @current-change="handleApplyCurrentChange"
            />
          </div>
        </el-card>
      </div>

      <!-- 外出记录 -->
      <div class="outing-section">
        <el-card class="outing-card">
          <template #header>
            <div class="card-header">
              <span>外出记录</span>
              <div class="filter-actions">
                <el-select v-model="recordFilter.status" placeholder="外出状态" style="width: 120px">
                  <el-option label="全部" value=""></el-option>
                  <el-option label="外出中" value="outing"></el-option>
                  <el-option label="已返回" value="returned"></el-option>
                  <el-option label="逾期未归" value="overdue"></el-option>
                </el-select>
                <el-button type="primary" @click="loadOutingRecords">搜索</el-button>
              </div>
            </div>
          </template>

          <el-table :data="outingRecordList" v-loading="recordLoading">
            <el-table-column type="index" label="序号" width="60" align="center" />
            <el-table-column prop="elderName" label="老人姓名" width="100" align="center" />
            <el-table-column prop="caregiverName" label="负责护工" width="100" align="center" />
            <el-table-column prop="caregiverPhone" label="护工电话" width="120" align="center" />
            <el-table-column prop="outingReason" label="外出事由" min-width="150" show-overflow-tooltip />
            <el-table-column prop="outingTime" label="外出时间" width="180" align="center">
              <template #default="{ row }">
                {{ formatDateTime(row.outingTime) }}
              </template>
            </el-table-column>
            <el-table-column prop="expectedReturnTime" label="预计返回" width="180" align="center">
              <template #default="{ row }">
                {{ formatDateTime(row.expectedReturnTime) }}
              </template>
            </el-table-column>
            <el-table-column prop="actualReturnTime" label="实际返回" width="180" align="center">
              <template #default="{ row }">
                {{ row.actualReturnTime ? formatDateTime(row.actualReturnTime) : '-' }}
              </template>
            </el-table-column>
            <el-table-column prop="outingStatus" label="外出状态" width="100" align="center">
              <template #default="{ row }">
                <el-tag :type="getOutingStatusTag(row.outingStatus)">
                  {{ getOutingStatusText(row.outingStatus) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120" align="center" fixed="right">
              <template #default="{ row }">
                <el-button link type="primary" @click="viewRecordDetail(row)">
                  详情
                </el-button>
                <el-button link type="success" @click="handleReturn(row)" v-if="row.outingStatus === 'outing'">
                  销假
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <div class="pagination">
            <el-pagination
              v-model:current-page="recordPagination.current"
              v-model:page-size="recordPagination.size"
              :total="recordPagination.total"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleRecordSizeChange"
              @current-change="handleRecordCurrentChange"
            />
          </div>
        </el-card>
      </div>
    </div>

    <!-- 外出登记对话框 -->
    <el-dialog
      v-model="showRegisterDialog"
      title="外出登记"
      width="600px"
      :before-close="handleRegisterDialogClose"
    >
      <el-form :model="registerForm" :rules="registerRules" ref="registerFormRef" label-width="100px">
        <el-form-item label="老人ID" prop="elderId">
          <el-input
            v-model="registerForm.elderId"
            placeholder="请输入老人ID"
            @blur="loadElderInfo"
          />
        </el-form-item>

        <el-form-item label="老人姓名">
          <el-input v-model="elderInfo.name" disabled />
        </el-form-item>

        <el-form-item label="家属信息">
          <el-input v-model="elderInfo.familyInfo" disabled />
        </el-form-item>

        <el-form-item label="护工信息">
          <el-input v-model="elderInfo.caregiverInfo" disabled />
        </el-form-item>

        <el-form-item label="外出事由" prop="outingReason">
          <el-input
            v-model="registerForm.outingReason"
            type="textarea"
            :rows="3"
            placeholder="请输入外出事由"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="外出时间" prop="outingTime">
          <el-date-picker
            v-model="registerForm.outingTime"
            type="datetime"
            placeholder="选择外出时间"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="预计返回" prop="expectedReturnTime">
          <el-date-picker
            v-model="registerForm.expectedReturnTime"
            type="datetime"
            placeholder="选择预计返回时间"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="一键提醒">
          <el-checkbox v-model="registerForm.sendNotification">发送外出通知给家属</el-checkbox>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="showRegisterDialog = false">取消</el-button>
        <el-button type="primary" @click="registerOuting" :loading="registering">
          登记
        </el-button>
      </template>
    </el-dialog>

    <!-- 处理申请对话框 -->
    <el-dialog
      v-model="showApplyDialog"
      title="处理外出申请"
      width="500px"
    >
      <div class="apply-detail">
        <div class="detail-item">
          <label>老人姓名：</label>
          <span>{{ currentApply.elderName }}</span>
        </div>
        <div class="detail-item">
          <label>家属姓名：</label>
          <span>{{ currentApply.familyName }}</span>
        </div>
        <div class="detail-item">
          <label>家属电话：</label>
          <span>{{ currentApply.familyPhone }}</span>
        </div>
        <div class="detail-item">
          <label>外出事由：</label>
          <span>{{ currentApply.outingReason }}</span>
        </div>
        <div class="detail-item">
          <label>外出时间：</label>
          <span>{{ formatDateTime(currentApply.outingTime) }}</span>
        </div>
        <div class="detail-item">
          <label>预计返回：</label>
          <span>{{ formatDateTime(currentApply.expectedReturnTime) }}</span>
        </div>
      </div>

      <template #footer>
        <el-button @click="showApplyDialog = false">取消</el-button>
        <el-button type="danger" @click="handleApply('rejected')">拒绝</el-button>
        <el-button type="primary" @click="handleApply('approved')">批准</el-button>
      </template>
    </el-dialog>

    <!-- 销假对话框 -->
    <el-dialog
      v-model="showReturnDialog"
      title="外出销假"
      width="400px"
    >
      <el-form :model="returnForm" ref="returnFormRef" label-width="80px">
        <el-form-item label="老人姓名">
          <el-input v-model="currentRecord.elderName" disabled />
        </el-form-item>
        <el-form-item label="实际返回" prop="actualReturnTime">
          <el-date-picker
            v-model="returnForm.actualReturnTime"
            type="datetime"
            placeholder="选择实际返回时间"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="返回备注">
          <el-input
            v-model="returnForm.returnNotes"
            type="textarea"
            :rows="3"
            placeholder="请输入返回备注（可选）"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="showReturnDialog = false">取消</el-button>
        <el-button type="primary" @click="confirmReturn">确认销假</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { 
  getOutingApplies, 
  processOutingApply, 
  getOutingRecords, 
  registerOutingRecord,
  returnOutingRecord,
  extendOutingRecord 
} from '@/api/outing'
import { getElderInfo } from '@/api/reception'

const loading = ref(false)
const applyLoading = ref(false)
const recordLoading = ref(false)
const registering = ref(false)
const showRegisterDialog = ref(false)
const showApplyDialog = ref(false)
const showReturnDialog = ref(false)
const registerFormRef = ref()
const returnFormRef = ref()

// 外出申请数据
const outingApplyList = ref([])
const currentApply = ref({})

// 外出记录数据
const outingRecordList = ref([])
const currentRecord = ref({})

// 老人信息
const elderInfo = reactive({
  name: '',
  familyInfo: '',
  caregiverInfo: ''
})

// 筛选条件
const applyFilter = reactive({
  status: ''
})

const recordFilter = reactive({
  status: ''
})

// 分页
const applyPagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

const recordPagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 登记表单
const registerForm = reactive({
  elderId: '',
  outingReason: '',
  outingTime: '',
  expectedReturnTime: '',
  sendNotification: true
})

// 销假表单
const returnForm = reactive({
  actualReturnTime: '',
  returnNotes: ''
})

// 验证规则
const registerRules = {
  elderId: [
    { required: true, message: '请输入老人ID', trigger: 'blur' }
  ],
  outingReason: [
    { required: true, message: '请输入外出事由', trigger: 'blur' }
  ],
  outingTime: [
    { required: true, message: '请选择外出时间', trigger: 'change' }
  ],
  expectedReturnTime: [
    { required: true, message: '请选择预计返回时间', trigger: 'change' }
  ]
}

// 加载外出申请
const loadOutingApplies = async () => {
  applyLoading.value = true
  try {
    const params = {
      page: applyPagination.current,
      size: applyPagination.size,
      ...applyFilter
    }
    const response = await getOutingApplies(params)
    outingApplyList.value = response.data.records || []
    applyPagination.total = response.data.total || 0
  } catch (error) {
    ElMessage.error('加载外出申请失败：' + error.message)
  } finally {
    applyLoading.value = false
  }
}

// 加载外出记录
const loadOutingRecords = async () => {
  recordLoading.value = true
  try {
    const params = {
      page: recordPagination.current,
      size: recordPagination.size,
      ...recordFilter
    }
    const response = await getOutingRecords(params)
    outingRecordList.value = response.data.records || []
    recordPagination.total = response.data.total || 0
  } catch (error) {
    ElMessage.error('加载外出记录失败：' + error.message)
  } finally {
    recordLoading.value = false
  }
}

// 加载老人信息
const loadElderInfo = async () => {
  if (!registerForm.elderId) return
  
  try {
    const response = await getElderInfo(registerForm.elderId)
    const elder = response.data
    elderInfo.name = elder.name || ''
    elderInfo.familyInfo = `${elder.familyName || ''} ${elder.familyPhone || ''}`
    elderInfo.caregiverInfo = `${elder.caregiverName || ''} ${elder.caregiverPhone || ''}`
  } catch (error) {
    ElMessage.error('加载老人信息失败：' + error.message)
    resetElderInfo()
  }
}

// 重置老人信息
const resetElderInfo = () => {
  elderInfo.name = ''
  elderInfo.familyInfo = ''
  elderInfo.caregiverInfo = ''
}

// 外出登记
const registerOuting = async () => {
  if (!registerFormRef.value) return
  
  try {
    await registerFormRef.value.validate()
    registering.value = true
    
    const outingData = {
      ...registerForm,
      sendNotification: registerForm.sendNotification
    }
    
    await registerOutingRecord(outingData)
    ElMessage.success('外出登记成功')
    showRegisterDialog.value = false
    loadOutingRecords()
    resetRegisterForm()
  } catch (error) {
    if (error.errors) {
      ElMessage.error('请完善表单信息')
    } else {
      ElMessage.error('外出登记失败：' + error.message)
    }
  } finally {
    registering.value = false
  }
}

// 重置登记表单
const resetRegisterForm = () => {
  registerForm.elderId = ''
  registerForm.outingReason = ''
  registerForm.outingTime = ''
  registerForm.expectedReturnTime = ''
  registerForm.sendNotification = true
  resetElderInfo()
}

// 查看申请详情
const viewApplyDetail = (apply) => {
  currentApply.value = apply
  showApplyDialog.value = true
}

// 处理申请
const handleApply = async (status) => {
  try {
    await processOutingApply(currentApply.value.id, status)
    ElMessage.success(`外出申请${status === 'approved' ? '批准' : '拒绝'}成功`)
    showApplyDialog.value = false
    loadOutingApplies()
  } catch (error) {
    ElMessage.error('处理申请失败：' + error.message)
  }
}

// 延期外出
const extendOuting = async (apply) => {
  try {
    const { value: extendDays } = await ElMessageBox.prompt(
      '请输入延期天数',
      '延期外出',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^[1-9]\d*$/,
        inputErrorMessage: '请输入有效的天数'
      }
    )
    
    await extendOutingRecord(apply.id, parseInt(extendDays))
    ElMessage.success('外出延期成功')
    loadOutingApplies()
    loadOutingRecords()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('延期外出失败：' + error.message)
    }
  }
}

// 查看记录详情
const viewRecordDetail = (record) => {
  currentRecord.value = record
  // 可以在这里显示更详细的记录信息
  ElMessage.info(`查看外出记录详情：${record.elderName}`)
}

// 处理销假
const handleReturn = (record) => {
  currentRecord.value = record
  returnForm.actualReturnTime = new Date()
  showReturnDialog.value = true
}

// 确认销假
const confirmReturn = async () => {
  try {
    await returnOutingRecord(currentRecord.value.id, returnForm)
    ElMessage.success('销假成功')
    showReturnDialog.value = false
    loadOutingRecords()
    resetReturnForm()
  } catch (error) {
    ElMessage.error('销假失败：' + error.message)
  }
}

// 重置销假表单
const resetReturnForm = () => {
  returnForm.actualReturnTime = ''
  returnForm.returnNotes = ''
}

// 分页处理
const handleApplySizeChange = (size) => {
  applyPagination.size = size
  applyPagination.current = 1
  loadOutingApplies()
}

const handleApplyCurrentChange = (current) => {
  applyPagination.current = current
  loadOutingApplies()
}

const handleRecordSizeChange = (size) => {
  recordPagination.size = size
  recordPagination.current = 1
  loadOutingRecords()
}

const handleRecordCurrentChange = (current) => {
  recordPagination.current = current
  loadOutingRecords()
}

// 关闭登记对话框
const handleRegisterDialogClose = (done) => {
  ElMessageBox.confirm('确定要取消外出登记吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    resetRegisterForm()
    done()
  }).catch(() => {})
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  const date = new Date(dateTime)
  return date.toLocaleString('zh-CN')
}

// 获取申请状态标签
const getApplyStatusTag = (status) => {
  const statusMap = {
    pending: 'warning',
    approved: 'success',
    rejected: 'danger'
  }
  return statusMap[status] || 'info'
}

// 获取申请状态文本
const getApplyStatusText = (status) => {
  const statusMap = {
    pending: '待处理',
    approved: '已批准',
    rejected: '已拒绝'
  }
  return statusMap[status] || status
}

// 获取外出状态标签
const getOutingStatusTag = (status) => {
  const statusMap = {
    outing: 'warning',
    returned: 'success',
    overdue: 'danger'
  }
  return statusMap[status] || 'info'
}

// 获取外出状态文本
const getOutingStatusText = (status) => {
  const statusMap = {
    outing: '外出中',
    returned: '已返回',
    overdue: '逾期未归'
  }
  return statusMap[status] || status
}

// 初始化加载
onMounted(() => {
  loadOutingApplies()
  loadOutingRecords()
})
</script>

<style scoped>
.reception-outing {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.outing-section {
  margin-bottom: 20px;
}

.outing-card {
  border-radius: 8px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filter-actions {
  display: flex;
  gap: 10px;
  align-items: center;
}

.pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.apply-detail {
  padding: 10px 0;
}

.detail-item {
  display: flex;
  margin-bottom: 12px;
  line-height: 1.5;
}

.detail-item label {
  width: 80px;
  font-weight: bold;
  color: #606266;
}

.detail-item span {
  flex: 1;
  color: #303133;
}
</style>
